package timerservice;



import log.Log;
import log.LoggerFactory;
import timerservice.util.IDCodeUtil;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.TimerTask;

/**
 * 定时任务管理器
 */
public class TimerTaskManager {
    //日志输出
    static Log logger = LoggerFactory.newInstance(TimerTaskManager.class);

    static TimerTaskManager timerTaskManager = new TimerTaskManager();
    boolean series = false;//串行执行吗
    Deque<MyTimerTask> taskQue = new ArrayDeque();//任务队列
    MyTimerTask runingTimerTask=null;//正在运行的任务
    HashMap<String, TimerTask> hmTimerTask = new HashMap<>();
    SwTimer timer = null;

    public TimerTaskManager() {
        timer = new SwTimer();
    }

    /**
     * 以单例模式返回全局唯一的TimerTaskManager实例
     */
    public static TimerTaskManager getTimerTaskManager() {
        return timerTaskManager;
    }

    /**
     * 添加定时任务
     */
    public String addTimerTask(MyTimerTask timerTask) {
        String id = timerTask.getTaskCode();
        if (id == null || id.trim().equals("")) {
            id = IDCodeUtil.generateUniqueID();
        }
        if (addTimerTask(id, timerTask)) {
            return id;
        }
        return null;
    }

    /**
     * 添加定时任务
     */
    private boolean addTimerTask(String taskCode, MyTimerTask timerTask) {
        synchronized (this) {
            if (hmTimerTask.containsKey(taskCode.toLowerCase())) {
                return false;
            }
            hmTimerTask.put(taskCode, timerTask);
            if (series) {
                taskQue.push(timerTask);
                startQue();
            } else {
                timer.schedule(timerTask);
            }
        }

        return true;
    }

    /**
     * 删除定时任务
     */
    public void deleteTimerTaskByCode(String taskCode, boolean cancelTask) {
        TimerTask timerTask = hmTimerTask.get(taskCode);
        if (timerTask != null) {
            if (cancelTask) {
                timerTask.cancel();
            }
            hmTimerTask.remove(taskCode);
        }
    }

    public void setSeries(boolean b) {
        this.series = b;
    }
    public void startQue(){
        if (taskQue.isEmpty()) {
            logger.e("串行任务队列执行完毕！");
            logger.i("检查并行任务");
            if (hmTimerTask.isEmpty()){
                logger.e("----------------并行任务执行完毕----------------------");
                logger.e("----------------程序退出----------------------");
                timer.cancel();
                System.exit(0);
            }
            hmTimerTask.forEach((s, timerTask) -> {
                logger.w("任务："+s+" 正在运行");
            });
            return;
        }
        if (runingTimerTask==null){
            MyTimerTask pop = taskQue.pop();
            runingTimerTask=pop;
            logger.w("--------------------------------------");
            logger.w("任务："+pop.taskCode+" 将会被执行");
            logger.w("--------------------------------------");
            pop.setOnQueCompleteListener((taskCode1, targetCount) -> {
                runingTimerTask=null;
                startQue();
            });
            timer.schedule(pop);
        }
    }
}